import requests
import json
import os

class DeepSeek:
    def __init__(self, api_key):
        self.api_key = api_key
        self.api_url = "https://api.deepseek.com/v1/chat/completions"
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
    
    def generate(self, prompt, model="deepseek-chat", max_tokens=2000, temperature=0.7):
        """调用DeepSeek API生成文本"""
        try:
            payload = {
                "model": model,
                "messages": [
                    {"role": "user", "content": prompt}
                ],
                "max_tokens": max_tokens,
                "temperature": temperature
            }
            
            response = requests.post(
                self.api_url,
                headers=self.headers,
                data=json.dumps(payload)
            )
            
            if response.status_code == 200:
                result = response.json()
                return result["choices"][0]["message"]["content"]
            else:
                print(f"API调用失败: {response.status_code} - {response.text}")
                return None
                
        except Exception as e:
            print(f"API调用异常: {str(e)}")
            return None

if __name__ == "__main__":
    # 测试代码
    api_key = os.getenv("DEEPSEEK_API_KEY")
    client = DeepSeek(api_key)
    response = client.generate("你好，请简要介绍一下自己。")
    print(response)